﻿using System;
using System.Collections.Generic;
using System.Text;

using Newtonsoft.Json.Linq;
using Newtonsoft.Json;

namespace System
{
    public class ArrayJsonConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return true;
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            object obj = serializer.Deserialize(reader);
            if (obj == null)
                return null;
            if (obj is JArray)
            {
                var list = new List<string>();
                foreach (JToken item in obj as JArray)
                {
                    if (!string.IsNullOrEmpty(item.ToString()))
                    {
                        list.Add(item.ToString());
                    }
                }
                return string.Join(",", list);
            }
            throw new JsonReaderException("不是有效的数组类型");
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            try
            {
                serializer.Serialize(writer, value.ToString().Split(',', StringSplitOptions.RemoveEmptyEntries));
            }
            catch
            {
                serializer.Serialize(writer, new int[0]);
            }
        }
    }
}
